<template>
  <div class="container">
    <div class="card">
      <h2>用户注册</h2>
      <form @submit.prevent="handleRegister">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            type="text"
            id="username"
            v-model="username"
            required
            placeholder="请选择用户名"
          />
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <input
            type="password"
            id="password"
            v-model="password"
            required
            placeholder="请设置密码"
          />
        </div>
        <div class="form-group">
          <label for="confirmPassword">确认密码</label>
          <input
            type="password"
            id="confirmPassword"
            v-model="confirmPassword"
            required
            placeholder="请再次输入密码"
          />
        </div>
        <button type="submit" class="btn btn-primary">注册</button>
      </form>
      <p class="mt-3">
        已有账号？
        <router-link to="/login">立即登录</router-link>
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import api from '../api/config'

const router = useRouter()
const username = ref('')
const password = ref('')
const confirmPassword = ref('')

const handleRegister = async () => {
  if (password.value !== confirmPassword.value) {
    alert('两次输入的密码不一致！')
    return
  }

  try {
    const response = await api.post('http://172.31.53.239:5000/api/register', {
      username: username.value,
      password: password.value
    })
    
    if (response.data.success) {
      alert('注册成功！请登录')
      router.push('/login')
    } else {
      alert(response.data.message || '注册失败，请稍后重试')
    }
  } catch (error) {
    console.error('注册失败:', error)
    if (error.response) {
      alert(error.response.data.message || '注册失败，请稍后重试')
    } else {
      alert('网络错误，请检查网络连接')
    }
  }
}
</script>

<style scoped>
.mt-3 {
  margin-top: 1rem;
}
</style> 